<template>
	<a-modal v-bind="options">
		<a-form ref="formRef" layout="vertical" :model="formState" :rules="rules">
			<a-typography-paragraph strong>
				<blockquote>员工信息</blockquote>
			</a-typography-paragraph>
			<a-row :gutter="12">
				<a-col :span="12">
					<a-form-item ref="employeeName" label="姓名" name="employeeName">
						<a-input-group compact class="display-flex">
							<a-input :maxlength="20" v-model:value="formState.employeeName" style="flex: 1" placeholder="请输入员工姓名" />
							<a-form-item-rest>
								<a-radio-group v-model:value="formState.gender" button-style="solid">
									<a-radio-button :value="1">男</a-radio-button>
									<a-radio-button :value="2">女</a-radio-button>
								</a-radio-group>
							</a-form-item-rest>
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item ref="phone" label="电话" name="phone">
						<a-input v-model:value="formState.phone" placeholder="请输入员工电话" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item ref="identityCard" label="证件信息" name="identityCard">
						<a-input-group compact>
							<a-select v-model:value="formState.certificationType" :options="certificationTypeOptions" style="width:116px"></a-select>
							<a-input v-model:value.trim="formState.identityCard" :maxlength="18" placeholder="请输入证件号码" style="width:172px"/>
						</a-input-group>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="劳动合同有效期">
						<a-range-picker :value-format="DATE_FORMAT.DATE" v-model:value="enterpriseInformation.time" />
					</a-form-item>
				</a-col>
			</a-row>
			<a-typography-paragraph strong>
				<blockquote>企业信息</blockquote>
			</a-typography-paragraph>
			<a-row :gutter="12">
				<a-col :span="12">
					<a-form-item ref="enterPriseId" label="所属企业" name="enterPriseId">
						<a-select
							show-search
							placeholder="请选择所属企业"
							option-filter-prop="label"
							v-model:value="formState.enterPriseId"
							size="default"
							@change="changeEnterprise"
							:options="enterprisesOptions"></a-select>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="统一社会信用代码">
						<a-input v-model:value="enterpriseInformation.creditCode" placeholder="选择企业后自动填充" :disabled="true" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="联系人姓名">
						<a-input v-model:value="enterpriseInformation.contactName" :disabled="true" placeholder="选择企业后自动填充" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="联系人手机号">
						<a-input v-model:value="enterpriseInformation.contactTel" :disabled="true" placeholder="选择企业后自动填充" />
					</a-form-item>
				</a-col>
			</a-row>
			<a-typography-paragraph strong>
				<blockquote>附件信息</blockquote>
			</a-typography-paragraph>
			<a-col :span="24">
				<a-form-item label="在职证明" name="attachmentIds">
					<a v-if="props.id !== ''" @click="record.attachment = true">查看附件</a>
					<a-button style="width: 33.33%" block v-else type="primary" @click="record.attachment = true">
						<check-outlined v-if="formState.attachmentIds?.length" />
						<plus-outlined v-else />
					</a-button>
				</a-form-item>
			</a-col>
		</a-form>
		<!-- 上传附件 -->
		<file-upload-dialog v-model:visible="record.attachment" v-model:files="formState.attachmentIds" :biz-id="props.id" />
	</a-modal>
</template>

<script setup lang="ts">
	import {reactive, ref, toRef, watch, onMounted} from 'vue'
	import DATE_FORMAT from 'yuxin-base/src/utils/date'
	import {Rule} from 'ant-design-vue/es/form'
	import {checkIdCard} from '@/utils/check'
	import {CheckOutlined, PlusOutlined} from '@ant-design/icons-vue'
	import FileUploadDialog from '@/components/common/file-upload-dialog.vue'
	import {addEmployee, enterpriseInformationFun, staffDetails, updateStaff} from '@/api/staff-pool'
	import {ValidateErrorEntity} from 'ant-design-vue/es/form/interface'
	import {enterpriseList} from '@/api/enterprise-library'
	import {validatePhone} from '@/utils/formValidation'

	const emits = defineEmits(['update:visible', 'close'])
	const props = defineProps<{
		visible: boolean
		id: string
	}>()

	interface FormState {
		employeeName: string | null
		phone: string | null
		certificationType: number,
		identityCard: string | null
		gender: number | null
		laborContractBeginTime: string | null
		laborContractEndTime: string | null
		enterPriseId: string | null
		enterPriseName: string | null
		employeeId: string | null
		attachmentIds: any[]
	}

	const record = reactive<any>({
		attachment: false,
		// 合同附件
		attachments: [],
		upload: false
	})

	const formState = ref<FormState>({
		employeeName: null,
		employeeId: null,
		phone: null,
		certificationType: 1,
		identityCard: null,
		gender: 1,
		laborContractBeginTime: null,
		laborContractEndTime: null,
		//所属企业
		enterPriseName: null,
		enterPriseId: null,
		attachmentIds: []
	})

	const enterpriseInformation = ref<any>({
		time: [],
		//信用代码
		creditCode: '',
		// 联系人姓名
		contactName: '',
		contactTel: ''
	})

	const rules = {
		employeeName: [{required: true, message: '请输入员工姓名', trigger: 'blur'}],
		phone: [{required: true, validator: validatePhone}],
		enterPriseId: [{required: true, message: '请选择所属企业', trigger: 'change'}],
		identityCard: [
			{
				required: true,
				validator(rule: Rule, value: string) {
					if (!value) {
						return Promise.reject('请输入证件号码')
					}

					if (formState.value.certificationType === 1 && !checkIdCard(value)) {
						return Promise.reject('身份证号不合法')
					} else {
						return Promise.resolve()
					}
				}
			}
		]
		// attachmentIds: [
		// 	{
		// 		required: true,
		// 		validator(rule: Rule, value: string) {
		// 			if (formState.value.attachmentIds.length === 0) {
		// 				return Promise.reject('请上传在职证明')
		// 			} else {
		// 				return Promise.resolve()
		// 			}
		// 		}
		// 	}
		// ]
	}

	const certificationTypeOptions = [
		{value: 1, label: '身份证'},
		{value: 2, label: '护照'},
		{value: 3, label: '港澳通行证'},
		{value: 4, label: '台湾同胞证'},
		{value: 5, label: '军官证'},
		{value: 6, label: '其他证件'}
	]

	const options = reactive({
		width: 640,
		title: '添加员工',
		centered: true,
		maskClosable: false,
		destroyOnClose: true,
		visible: toRef(props, 'visible'),
		onCancel() {
			formState.value.attachmentIds = []
			emits('update:visible', false)
			setTimeout(() => emits('close'), 100)
		},
		onOk() {
			formRef.value
				.validate()
				.then(() => {
					formState.value.attachmentIds = formState.value.attachmentIds.map(e => e.id)

					formState.value.laborContractBeginTime = enterpriseInformation.value.time ? enterpriseInformation.value.time[0] : ''
					formState.value.laborContractEndTime = enterpriseInformation.value.time ? enterpriseInformation.value.time[1] : ''

					if (props.id === '') {
						addEmployee(formState.value).finally(() => emits('close'))
					} else {
						//重新编辑
						emits('update:visible', false)
						updateStaff(formState.value).finally(() => emits('close'))
					}
				})
				.catch((error: ValidateErrorEntity<FormState>) => {
					console.log('error', error)
				})
		}
	})

	const enterprisesOptions = ref([])

	const formRef = ref()

	const changeEnterprise = () => {
		getEnterpriseInformation(formState.value.enterPriseId as string)
	}
	//企业相关信息
	const getEnterpriseInformation = (id: string) => {
		enterpriseInformationFun(id).then(res => {
			enterpriseInformation.value.contactName = res.data.linkmanName
			enterpriseInformation.value.contactTel = res.data.linkmanPhone
			enterpriseInformation.value.creditCode = res.data.societyCode
		})
	}
	const getFun = () => {
		enterpriseList().then((res: any) => {
			enterprisesOptions.value = res.data.map((e: any) => {
				return {
					label: e.enterPriseName,
					value: e.id
				}
			})
		})
	}

	watch(
		() => props.visible,
		newVal => {
			if (newVal) {
				getFun()
				if (props.id !== '') {
					options.title = '编辑员工'
					// 重新编辑
					updateEmployee()
				}
			} else {
				cancel()
			}
		}
	)
	const cancel = () => {
		formState.value.attachmentIds = []
		formState.value.employeeId = null
		formState.value.employeeName = null
		formState.value.phone = null
		formState.value.certificationType = 1
		formState.value.identityCard = null
		formState.value.gender = 1
		formState.value.laborContractBeginTime = null
		formState.value.laborContractEndTime = null
		formState.value.enterPriseId = null
		formState.value.enterPriseName = null
		enterpriseInformation.value.time = []
		enterpriseInformation.value.creditCode = null
		enterpriseInformation.value.contactName = null
		enterpriseInformation.value.contactTel = null
	}

	// 从新编辑
	const updateEmployee = () => {
		staffDetails(props.id).then(res => {
			console.log(res)
			formState.value.attachmentIds = res.data.employeeImgDTOS || []
			formState.value.employeeId = res.data.employeeId
			formState.value.employeeName = res.data.employeeName
			formState.value.phone = res.data.phone
			formState.value.certificationType = res.data.certificationType
			formState.value.identityCard = res.data.identityCard
			formState.value.gender = res.data.gender
			formState.value.laborContractBeginTime = res.data.laborContractBeginTime
			formState.value.laborContractEndTime = res.data.laborContractEndTime
			formState.value.enterPriseId = res.data.enterPriseId
			formState.value.enterPriseName = res.data.enterPriseId
			enterpriseInformation.value.time[0] = res.data.laborContractBeginTime
			enterpriseInformation.value.time[1] = res.data.laborContractEndTime
			enterpriseInformation.value.creditCode = res.data.societyCode
			enterpriseInformation.value.contactName = res.data.linkmanName
			enterpriseInformation.value.contactTel = res.data.linkmanPhone
		})
	}
</script>

<style lang="less" scoped>
	.display-flex {
		flex: 1;
		justify-content: space-around;
	}
</style>
